<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.png">
  <link rel="mask-icon" href="/images/avatar.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"notes.maxwi.com","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":true,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="面向对象编程（OOP）和泛型编程都能处理在编写程序时不知道类型的情况。不同之处是OOP能处理类型在程序运行之前都未知的情况（即通过多态的动态绑定）；而泛型编程中，在编译时就能确定类型，只是可以应用于不同的类型，例如vector可以放int，也可以放string等。既可以定义函数模板也可以定义类模板。 函数模板1.一个函数模板就相当于一个公式，用来生成针对特定类型的函数版本。模板定义以关键字temp">
<meta property="og:type" content="article">
<meta property="og:title" content="C++学习笔记之模板与泛型编程">
<meta property="og:url" content="http://notes.maxwi.com/2016/01/23/cpp-oop-template/index.html">
<meta property="og:site_name" content="blueyi&#39;s notes">
<meta property="og:description" content="面向对象编程（OOP）和泛型编程都能处理在编写程序时不知道类型的情况。不同之处是OOP能处理类型在程序运行之前都未知的情况（即通过多态的动态绑定）；而泛型编程中，在编译时就能确定类型，只是可以应用于不同的类型，例如vector可以放int，也可以放string等。既可以定义函数模板也可以定义类模板。 函数模板1.一个函数模板就相当于一个公式，用来生成针对特定类型的函数版本。模板定义以关键字temp">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2016-01-23T08:21:39.000Z">
<meta property="article:modified_time" content="2016-01-23T08:21:39.000Z">
<meta property="article:author" content="blueyi">
<meta property="article:tag" content="Notes">
<meta property="article:tag" content="CPP-OOP">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://notes.maxwi.com/2016/01/23/cpp-oop-template/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>C++学习笔记之模板与泛型编程 | blueyi's notes</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="blueyi's notes" type="application/atom+xml">
<link rel="alternate" href="/rss2.xml" title="blueyi's notes" type="application/rss+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">blueyi's notes</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Follow Excellence,Success will chase you!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="http://notes.maxwi.com/2016/01/23/cpp-oop-template/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/default_avatar.jpg">
      <meta itemprop="name" content="blueyi">
      <meta itemprop="description" content="心怀善意，虛怀若谷！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="blueyi's notes">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          C++学习笔记之模板与泛型编程
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2016-01-23 16:21:39" itemprop="dateCreated datePublished" datetime="2016-01-23T16:21:39+08:00">2016-01-23</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/C/" itemprop="url" rel="index"><span itemprop="name">C++</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="Symbols count in article">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">Symbols count in article: </span>
              <span>16k</span>
            </span>
            <span class="post-meta-item" title="Reading time">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">Reading time &asymp;</span>
              <span>14 mins.</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>面向对象编程（OOP）和泛型编程都能处理在编写程序时不知道类型的情况。不同之处是OOP能处理类型在程序运行之前都未知的情况（即通过多态的动态绑定）；而泛型编程中，在编译时就能确定类型，只是可以应用于不同的类型，例如vector可以放int，也可以放string等。<br>既可以定义函数模板也可以定义类模板。</p>
<h2 id="函数模板"><a href="#函数模板" class="headerlink" title="函数模板"></a>函数模板</h2><p>1.一个函数模板就相当于一个公式，用来生成针对特定类型的函数版本。模板定义以关键字template开始，后跟一个模板参数列表（template parameter list），多个模板参数需要由逗号分割，使用尖括号包围起来，参数列表不能为空，模板参数表示在类或函数中用到的类型或值，当使用模板时，隐式或显示地指定模板实参（template argument），将其绑定到模板参数上。eg: </p>
<span id="more"></span>

<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//声明一个函数模板，该函数接受一个参数类型为T的指针，返回值类型为T</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="function">T <span class="title">foo</span><span class="params">(T* p)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> *p;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2.当编译器实例化一个模板时，它使用实际的模板实参代替对应的模板参数来创建出模板的一个新”实例“。  </p>
<p>3.模板的类型参数T可以用来指定返回类型和函数的参数类型，以及在函数体内用于变量声明或类型转换。  </p>
<p>4.类型参数前必须使用关键字class或typename。这个两个关键字的含义完全相同。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T, <span class="keyword">class</span> <span class="title class_">U</span>&gt; <span class="built_in">calc</span> (<span class="type">const</span> T&amp;, <span class="type">const</span> U&amp;);</span><br></pre></td></tr></table></figure>

<p>5.除了定义类型参数外，还可以使用模板定义非类型参数（nontype parameter）,一个非类型实参是一个值而非一个类型，非类型实参使用一个特定的类型名而非关键字class或typename来指定。传递给非类型实参的值必须是常量表达式。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//N和M可以是任意两个能被编译器推断出类型的常量表达式</span></span><br><span class="line"><span class="comment">//由于不能拷贝数组，所以将类型定义为const的引用</span></span><br><span class="line"><span class="keyword">template</span>&lt;<span class="type">unsigned</span> N, <span class="type">unsigned</span> M&gt;  <span class="comment">//该行与下一行不强制换行</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">compare</span><span class="params">(<span class="type">const</span> <span class="type">char</span> (&amp;p1)[N], <span class="type">const</span> <span class="type">char</span> (&amp;p2)[M])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">strcmp</span>(p1, p2);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//调用</span></span><br><span class="line"><span class="comment">//编译器将自动推断出所需要的N和M是字符串的大小+1</span></span><br><span class="line"><span class="built_in">compare</span>(<span class="string">&quot;hi&quot;</span>, <span class="string">&quot;mom&quot;</span>);</span><br><span class="line"><span class="comment">//编译器实例化的版本如下</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">compare</span><span class="params">(<span class="type">const</span> <span class="type">char</span> (&amp;p1)[<span class="number">3</span>], <span class="type">const</span> <span class="type">char</span> (&amp;p2)[<span class="number">3</span>])</span></span></span><br></pre></td></tr></table></figure>

<p>6.一个非类型实参可以是一个整型，或者是一个指向对象或函数类型的指针或（左值）引用。但必须是一个常量表达式。  </p>
<p>7.函数模板可以声明为inline或constexpr的，这两个关键字必须放在模板参数列表之后，返回类型之前。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="function"><span class="keyword">inline</span> T <span class="title">min</span><span class="params">(<span class="type">const</span> T&amp;, <span class="type">const</span> T&amp;)</span></span>;</span><br></pre></td></tr></table></figure>

<p>8.模板程序应该尽量减少对实参类型的要求，例如可以考虑使用functional头文件中支持比较指针的比较模板。</p>
<p>9.函数模板和类模板成员函数的定义通常放在头文件中。当编译器遇到一个模板定义时，它并不生成代码，只有当实例化出一个特定版本时，编译器才会生成模板。</p>
<p>10.保证传递给模板的实参支持模板所要求的操作，以及这些操作在模板中能正确工作是调用者的责任。  </p>
<h2 id="类模板"><a href="#类模板" class="headerlink" title="类模板"></a>类模板</h2><p>1.类模板的定义与使用和函数模板类似，注意在类模板的继承关系中，子类模板不能直接访问父类的成员，需要使用this指针，或者间接访问运算符。所以定义如下：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">class</span> <span class="title class_">Base_temp</span> &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Base_temp</span>() = <span class="keyword">default</span>;</span><br><span class="line">    <span class="built_in">Base_temp</span>(T i, T j) : <span class="built_in">x</span>(i), <span class="built_in">y</span>(j) &#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    T x;</span><br><span class="line">    T y;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">class</span> <span class="title class_">Driv</span> : <span class="keyword">public</span> Base_temp&lt;T&gt; &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Driv</span>() = <span class="keyword">default</span>;</span><br><span class="line">    <span class="built_in">Driv</span>(T i, T j, T k) : <span class="built_in">Base_temp</span>&lt;T&gt;(i, j), <span class="built_in">z</span>(k) &#123;&#125;</span><br><span class="line">    <span class="comment">//</span></span><br><span class="line">    <span class="function"><span class="type">void</span> <span class="title">modify</span><span class="params">(std::ostream &amp;os)</span> </span>&#123; os &gt;&gt; <span class="keyword">this</span>-&gt;i &gt;&gt; Base_temp&lt;T&gt;::j &gt;&gt; k; &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    T z;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>2.编译器不能为类模板推断类型，所是使用时需要通过尖括号提供类型信息，例如<code>Driv&lt;int&gt; driv(1, 2, 3);</code></p>
<p>3.定义在类模板之外的成员函数必须以template开始，后接类模板参数列表，并且类名后面也要有尖括号提供类型信息，形如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line">ret-type class_name&lt;T&gt;::member-<span class="built_in">name</span>(parm-list)</span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="type">void</span> Blob&lt;T&gt;::<span class="built_in">check</span>(size_type i, <span class="type">const</span> std::string &amp;msg) <span class="type">const</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">if</span> (i &gt;= data-&gt;<span class="built_in">size</span>())</span><br><span class="line">      <span class="keyword">throw</span> std::<span class="built_in">out_of_range</span>(msg);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.默认情况下，对于一个实例化了的类模板，其成员只有在使用时才被实例化。</p>
<p>5.在类模板的作用域内，可以直接使用模板名而不必指定模板实参。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line">BlobPtr&lt;T&gt; BlobPtr&lt;T&gt;::<span class="keyword">operator</span>++(<span class="type">int</span>)</span><br><span class="line">&#123;</span><br><span class="line">  BlobPtr ret = *<span class="keyword">this</span>;  <span class="comment">//直接使用模板名，而无需提供模板实参</span></span><br><span class="line">  ++*<span class="keyword">this</span>;</span><br><span class="line">  <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="模板与友元"><a href="#模板与友元" class="headerlink" title="模板与友元"></a>模板与友元</h2><p>1.当一个类包含友元声明时，类与友元各自是否是模板是相互无关的。如果一个类模板包含一个非模板友元，则友元被授权可以访问所有模板实例。如果友元自身是模板，类可以授权给所有友元模板实例，也可以只授权给特定实例。<br>为了引用（类或函数）模板的一个特定实例，必须首先声明模板自身。如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//前置声明，在Blob中声明友元所需要的</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span>&gt; <span class="keyword">class</span> <span class="title class_">BlobPtr</span>;</span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span>&gt; <span class="keyword">class</span> <span class="title class_">Blob</span>;</span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line">  <span class="type">bool</span> <span class="keyword">operator</span>==(<span class="type">const</span> Blob&lt;T&gt;&amp;, <span class="type">const</span> Blob&lt;T&gt;&amp;);</span><br><span class="line"><span class="comment">//类及其友元声明</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">class</span> <span class="title class_">Blob</span> &#123;</span><br><span class="line">  <span class="comment">//每个Blob实例将访问权限授予用相同类型实例化的BlobPtr和相等运算符</span></span><br><span class="line">  <span class="keyword">friend</span> <span class="keyword">class</span> <span class="title class_">BlobPtr</span>&lt;T&gt;;</span><br><span class="line">  <span class="keyword">friend</span> <span class="type">bool</span> <span class="keyword">operator</span>==&lt;T&gt;(<span class="type">const</span> Blob&lt;T&gt;&amp;, <span class="type">const</span> Blob&lt;T&gt;&amp;);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><strong>注意:每个Blob实例将访问权限授予用相同类型实例化的BlobPtr和相等运算符，即一对一的友好关系</strong></p>
<p>2.一个类也可以将另一个模板的每个实例都声明为自己的友元，或者限定特定的实例为友元。如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//前置声明，后面将用类C实例化的pal声明为C的一个友元</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">class</span> <span class="title class_">Pal</span>;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">C</span> &#123; <span class="comment">//C是一个普通的非模板类</span></span><br><span class="line">  <span class="keyword">friend</span> <span class="keyword">class</span> <span class="title class_">Pal</span>&lt;C&gt;;  <span class="comment">//用类C实例化的Pal是C的一个友元</span></span><br><span class="line">  <span class="comment">// Pal2的所有实例都是C的友元，这种情况无法前置声明</span></span><br><span class="line">  <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">friend</span> <span class="keyword">class</span> <span class="title class_">Pal2</span>;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">class</span> <span class="title class_">C2</span> &#123; <span class="comment">//C2本身是一个类模板</span></span><br><span class="line"><span class="comment">//C2的每个实例将相同实例化的Pal声明为友元</span></span><br><span class="line">  <span class="keyword">friend</span> <span class="keyword">class</span> <span class="title class_">Pal</span>&lt;T&gt;; <span class="comment">//Pal的模板声明必须在作用域之内</span></span><br><span class="line">  <span class="comment">//Pal2的所有实例都是C2的每个实例的友元，不需要前置声明</span></span><br><span class="line">  <span class="keyword">template</span> &lt;<span class="keyword">typename</span> X&gt; <span class="keyword">friend</span> <span class="keyword">class</span> <span class="title class_">Pal2</span>;</span><br><span class="line">  <span class="comment">//Pal3是一个非模板类，它是C2所有实例的友元</span></span><br><span class="line">  <span class="keyword">friend</span> <span class="keyword">class</span> <span class="title class_">Pal3</span>;   <span class="comment">//不需要Pal3的前置声明</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><strong>为了让所有实例成为友元，友元声明中必须使用与类模板本身不同的模板参数。</strong><br>3.令模板自己的类型参数成为友元（C++11）：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> Type&gt; <span class="keyword">class</span> <span class="title class_">Bar</span> &#123;</span><br><span class="line"><span class="keyword">friend</span> Type;  <span class="comment">//将访问权限授予用来实例化Bar的类型</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>如对于某个类型名Foo，Foo将成为Bar<Foo>的友元</p>
<p>4.模板类型别名<br>可以使用typedef方式来引用补货化的类：<code>typedef Bolb&lt;string&gt; StrBlob;</code>，但由于模板不是类型，所以不能定义一个typedef引用一个模板,即无法定义一个typedef引用Blob<T>。但C++11中可以使用using为类模板定义一个类型别名：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt; <span class="keyword">using</span> twin = pair&lt;T, T&gt;;</span><br><span class="line">twin&lt;string&gt; authors; <span class="comment">//authors是一个pair&lt;string, string&gt;</span></span><br></pre></td></tr></table></figure>
<p>当定义一个模板类型别名时，可以固定一个或多个模板参数：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">using</span> partNo = pair&lt;T, <span class="type">unsigned</span>&gt;;</span><br><span class="line">partNo&lt;string&gt; books; <span class="comment">//books是一个pair&lt;T, unsigned&gt;</span></span><br></pre></td></tr></table></figure>
<p>这种情况下必须指定pair的first成员，但不能指定pair的second成员</p>
<p>5.<strong>类模板可以定义static成员</strong>，当定义类模板的static成员时，该类模板实例化的每个实例类型都有一个独有的static对象，该实例类型的所有对象共有static成员。static成员的定义与定义模板的成员函数类似，定义的开始部分模板参数列表：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="type">size_t</span> Foo&lt;T&gt;::ctr = <span class="number">0</span>; <span class="comment">//定义并初始化ctr</span></span><br></pre></td></tr></table></figure>
<h2 id="模板参数"><a href="#模板参数" class="headerlink" title="模板参数"></a>模板参数</h2><p>1.类似函数参数的名字，模板参数的名字T并没有任何内存意义，可以使用任何合法的名字。</p>
<p>2.模板参数遵循普通的作用域规则，例如同样存在内层同名类型隐藏外层同名类型的情况</p>
<p>3.模板声明必须包含模板参数，与函数参数类似的是声明中的模板参数的名字不必与定义中相同：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//声明但不定义compare和Blob</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="function"><span class="type">int</span> <span class="title">compare</span><span class="params">(<span class="type">const</span> T&amp;, <span class="type">const</span> T&amp;)</span></span>;</span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">class</span> <span class="title class_">Blob</span>;</span><br></pre></td></tr></table></figure>
<p><strong>一个特定文件所需要的所有模板的声明通常一起放置在文件开始位置，出现于任何使用这些模板的代码之前.</strong><br>4.默认情况下，C++语言假定通过作用域运算符访问的名字不是类型，所以如果希望使用一个模板类型参数的类型成员，就必须显式告诉编译器该名字是一个类型，通过关键字typename来实现：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;  <span class="comment">//类型T含有成员value_type</span></span><br><span class="line"><span class="function"><span class="keyword">typename</span> T::value_type <span class="title">top</span><span class="params">(<span class="type">const</span> T&amp; c)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!c.<span class="built_in">empty</span>())</span><br><span class="line">    <span class="keyword">return</span> c.<span class="built_in">back</span>();</span><br><span class="line">  <span class="keyword">else</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">typename</span> T::value_type <span class="built_in">type</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当我们希望通知编译器一个名字表示类型时，必须使用关键字typename，而不能使用class</p>
<p>5.类似可以为函数参数提供默认实参一样，也可以提供<strong>默认模板实参</strong>，C++11中可以为函数和类模板提供默认实参，早期的C++只允许为类模板提供默认实参。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//compare有一个默认默认实参less&lt;T&gt;和一个默认函数实参F()</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T, <span class="keyword">typename</span> F = less&lt;T&gt;&gt;</span><br><span class="line"><span class="type">int</span> <span class="built_in">compare</span>(<span class="type">const</span> T &amp;v1, <span class="type">const</span> T &amp;v2, F f = <span class="built_in">F</span>())  <span class="comment">//默认函数实参指出f将绑定到一个函数对象</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">f</span>(v1, v2)) <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="keyword">if</span> (v2, v1) <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>调用方法为：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">bool</span> i = <span class="built_in">compare</span>(<span class="number">0</span>, <span class="number">42</span>);  <span class="comment">//使用less, i 为-1</span></span><br><span class="line"><span class="type">bool</span> j = <span class="built_in">compare</span>(item1, item2, compareIsbn);  <span class="comment">//item1和item2为自定义类型，compareIsbn为函数对象</span></span><br></pre></td></tr></table></figure>

<p>6.<strong>类模板的默认模板实参</strong>：无论何时使用类模板，都必须在模板名之后接上尖括号，尖括号指出类必须从一个模板实例化而来，特别是如果一个类模板为其所有模板参数都提供了默认实参，且我们希望使用这些默认实参，就必须在模板名之后跟一个空尖括号对：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">class</span> <span class="title class_">T</span> = <span class="type">int</span>&gt; <span class="keyword">class</span> Numbers &#123;  <span class="comment">//T默认为int</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">  <span class="built_in">Numbers</span>(T v = <span class="number">0</span>): <span class="built_in">va</span>(v) &#123;&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">  T val;</span><br><span class="line">&#125;;</span><br><span class="line">Numbers&lt;<span class="type">long</span> <span class="type">double</span>&gt; lots_of_precision;</span><br><span class="line">Numbers&lt;&gt; average_precision;  <span class="comment">//使用默认类型int</span></span><br></pre></td></tr></table></figure>
<h2 id="成员模板"><a href="#成员模板" class="headerlink" title="成员模板"></a>成员模板</h2><p>1.一个类（无论是普通类还是类模板）可以包含本身是模板的成员函数，这种成员函数被称为成员模板（member template）。成员模板不能是虚函数。</p>
<h3 id="普通（非模板）类的成员模板"><a href="#普通（非模板）类的成员模板" class="headerlink" title="普通（非模板）类的成员模板"></a>普通（非模板）类的成员模板</h3><p>正常定义成员模板即可，如下定义一个类DebugDelete来封装delete操作，使delete操作之前打印一打消息。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">DebugDelete</span> &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">  <span class="built_in">DebugDelete</span>(std::ostream &amp;s = std::cerr) : <span class="built_in">os</span>(s) &#123;&#125;</span><br><span class="line">  <span class="comment">//与任何函数模板相同，T的类型由编译器推断</span></span><br><span class="line">  <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="function"><span class="type">void</span> <span class="title">operator</span><span class="params">()</span><span class="params">(T *p)</span> <span class="type">const</span> </span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">    os &lt;&lt; <span class="string">&quot;deleting ptr&quot;</span> &lt;&lt; std::endl;</span><br><span class="line">    <span class="keyword">delete</span> p;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">  std::ostream &amp;os;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>用法：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">double</span> *p = <span class="keyword">new</span> <span class="type">double</span>;</span><br><span class="line">DebugDelete d;</span><br><span class="line"><span class="built_in">d</span>(p); <span class="comment">//调用DebugDelete::operator()(double*),释放p</span></span><br><span class="line"><span class="type">int</span> *ip = <span class="keyword">new</span> <span class="type">int</span>;</span><br><span class="line"><span class="built_in">DebugDelete</span>()(ip); <span class="comment">//在一个临时对象上调用函数对象</span></span><br></pre></td></tr></table></figure>

<h3 id="类模板的成员模板"><a href="#类模板的成员模板" class="headerlink" title="类模板的成员模板"></a>类模板的成员模板</h3><p>对于类模板，类和成员各自有自己的、独立的模板参数。定义方法如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">class</span> <span class="title class_">Blob</span> &#123;  <span class="comment">//定义模板类</span></span><br><span class="line">  <span class="keyword">template</span> &lt;<span class="keyword">typename</span> It&gt; <span class="built_in">Blob</span>(It b, It e);  <span class="comment">//声明类模板的成员模板</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在模板类外定义成员模板时，必须同时提供类模板和成员模板的参数列表：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;  <span class="comment">//类的类型参数</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> It&gt;  <span class="comment">//构造函数的类型参数</span></span><br><span class="line">  Blob&lt;T&gt;::<span class="built_in">Blob</span>(It b, It e):<span class="built_in">data</span>(std::make_shared&lt;std::vector&lt;T&gt;&gt;(b, e)) &#123;&#125;</span><br></pre></td></tr></table></figure>
<p>实例化成员模板时，必须同时提供类和函数模板的实参，如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> ia[] = &#123;<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;;</span><br><span class="line"><span class="function">Blob&lt;<span class="type">int</span>&gt; <span class="title">a1</span><span class="params">(begin(ia), end(ia))</span></span>;</span><br></pre></td></tr></table></figure>

<h2 id="使用extern控制实例化"><a href="#使用extern控制实例化" class="headerlink" title="使用extern控制实例化"></a>使用extern控制实例化</h2><p>由于模板被使用时才会进行实例化，意味着相同的实例可以出现在多个对象文件中，当两个或多个独立编译的源文件使用了相同的模板时，并提供了相同的模板参数时，每个文件都会有一个该模板的实例。C++11中可以通过extern来显式实例化(explicit instantiation)来避免这种开销。显示实例化形如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">extern</span> <span class="keyword">template</span> declaration;  <span class="comment">//实例化声明</span></span><br><span class="line"><span class="keyword">template</span> declaration;  <span class="comment">//实例化定义</span></span><br></pre></td></tr></table></figure>
<p>declaration是一个类或函数声明，其中所有模板参数已被替换为模板实参，例如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//实例化声明与定义</span></span><br><span class="line"><span class="keyword">extern</span> <span class="keyword">template</span> <span class="keyword">class</span> <span class="title class_">Blob</span>&lt;string&gt;;   <span class="comment">//声明</span></span><br><span class="line"><span class="function"><span class="keyword">template</span> <span class="type">int</span> <span class="title">compare</span><span class="params">(<span class="type">const</span> <span class="type">int</span>&amp;, <span class="type">const</span> <span class="type">int</span>&amp;)</span></span>;  <span class="comment">//定义</span></span><br></pre></td></tr></table></figure>
<p>当编译器遇到extern模板声明时，它不会在本文件中生成实例化代码，将一个实例化声明为extern就表示承诺在程序其他位置有文件实例化的一个非extern声明（定义）。对于一个给定的实例化版本，可能有多个extern声明，但必须只有一个定义。<br>由于编译器在使用一个模板时自动对其实例化，因此extern声明必须出现在任何使用些实例版本的代码之前。</p>
<h2 id="模板实参推断"><a href="#模板实参推断" class="headerlink" title="模板实参推断"></a>模板实参推断</h2><h3 id="指定显式模板实参"><a href="#指定显式模板实参" class="headerlink" title="指定显式模板实参"></a>指定显式模板实参</h3><p>可以为函数模板指定显式模板实参，以控制函数的返回类型与实例化<br>如下面定义的sum函数模板，接受两个不同类型的参数，并返回一个不同类型的结果：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T1, <span class="keyword">typename</span> T2, <span class="keyword">typename</span> T3&gt;</span><br><span class="line"><span class="function">T1 <span class="title">sum</span><span class="params">(T2, T3)</span></span>; <span class="comment">//由于参数列表中没有T1，所以编译器无法推断T1的类型，必须显式提供</span></span><br></pre></td></tr></table></figure>
<p>用法:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">auto</span> val3 = <span class="built_in">sum</span>&lt;<span class="type">double</span>&gt;(<span class="number">42</span>, <span class="number">33.2f</span>);  <span class="comment">//double sum(int, float)</span></span><br></pre></td></tr></table></figure>
<p>显式模板实参按由左至右的顺序与对应的模板参数匹配，只有尾部（最右）参数的显式模板实参才可以忽略，而且前提是它们可以从函数参数推断出来。如果sum函数模板中这样写<code>T3 sum(T2, T1)</code>，其他不变，则此时必须同时指定3个实参：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">auto</span> val2 = <span class="built_in">sum</span>&lt;<span class="type">double</span>, <span class="type">int</span>, <span class="type">float</span>&gt;(<span class="number">42</span>, <span class="number">33.2f</span>);</span><br></pre></td></tr></table></figure>
<p>对于指定了模板类型实参的函数实参会发生正常的类型转换。</p>
<h3 id="尾置返回类型与类型转换"><a href="#尾置返回类型与类型转换" class="headerlink" title="尾置返回类型与类型转换"></a>尾置返回类型与类型转换</h3><p><strong>通过尾置返回类型返回引用</strong><br>由于尾置返回出现在参数列表之后，它可以使用函数的参数，尾置返回允许我们在参数列表之后声明返回类型，并可以使用decltype来推断返回类型。例如编写一个函数，接受表示序列的一对迭代器，并返回序列中一个元素的引用，由于此时并不知道引用的类型，引用的类型只有在确定迭代器之后才能知道，这种情况就可以使用尾置返回，如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="function"><span class="keyword">auto</span> <span class="title">fcn</span><span class="params">(It beg, It end)</span> -&gt; <span class="title">decltype</span><span class="params">(*beg)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="comment">//处理序列</span></span><br><span class="line">  <span class="keyword">return</span> *beg;  <span class="comment">//返回序列中一个元素的引用</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>通过标准库的类型转换模板返回元素的值</strong><br>类似上面的情况，假如要返回元素的值，由于上述情况下迭代器的操作都不会生成元素，只能生成元素的引用，所以无法返回元素的值。可以使用标准库的类型转换模板来获得元素的类型，然后再返回一个值。该模板定义在头文件type_traits中。可以使用其中的remove_reference来获得元素的类型，该模板有一个模板类型参数和一个名为type的类型成员，如remove_reference&lt;int&amp;&gt;，则type成员将是int。如上例返回值而非引用，改写为：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="function"><span class="keyword">auto</span> <span class="title">fcn2</span><span class="params">(It beg, It end)</span> -&gt;</span></span><br><span class="line"><span class="function">  <span class="keyword">typename</span> remove_reference&lt;<span class="title">decltype</span><span class="params">(*beg)</span>&gt;::type</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> *beg;  <span class="comment">//返回序列中一个元素的拷贝</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="函数指针与实参推断"><a href="#函数指针与实参推断" class="headerlink" title="函数指针与实参推断"></a>函数指针与实参推断</h3><p>当用一个函数模板初始化一个函数指名或为一个函数指针赋值时，编译器使用指针的类型来推断模板实参。如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="function"><span class="type">int</span> <span class="title">compare</span><span class="params">(<span class="type">const</span> T&amp;, <span class="type">const</span> T&amp;)</span></span>;</span><br><span class="line"><span class="comment">//pf1指向实例int compare(const int&amp;, const int&amp;)</span></span><br><span class="line"><span class="built_in">int</span> (*pf1)(<span class="type">const</span> <span class="type">int</span>&amp;, <span class="type">const</span> <span class="type">int</span>&amp;) = compare;</span><br></pre></td></tr></table></figure>

<h3 id="函数模板实参推断与引用"><a href="#函数模板实参推断与引用" class="headerlink" title="函数模板实参推断与引用"></a>函数模板实参推断与引用</h3><p>1.对于带有引用类型的模板类型参数推断，首先需要明白两点：编译器会应用正常的引用绑定规则（即&amp;绑定到左值，const &amp;即可绑定到左值，又可绑定到右值，&amp;&amp;绑定到右值）；const是底层的，不是顶层的（即const是类型的一部分）。<br><strong>从左值引用函数参数推断类型</strong><br>当函数参数是模板类型参数的一个普通（左值）引用时（即，形如T&amp;），绑定规则告诉我们，只能传递给它一个左值（如，一个变量或一个返回引用类型的表达式）。实参可以是const类型，也可以不是。如果实参是const类型，则T将被推断为const类型。如：<br>f1为非const的普通引用</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="function"><span class="type">void</span> <span class="title">f1</span><span class="params">(T&amp;)</span></span>; <span class="comment">//实参必须是一个左值</span></span><br><span class="line"><span class="built_in">f1</span>(i);  <span class="comment">//i是一个int，则T为int</span></span><br><span class="line"><span class="built_in">f1</span>(ci); <span class="comment">//ci是一个const int;则T为const int</span></span><br><span class="line"><span class="built_in">f1</span>(<span class="number">5</span>);  <span class="comment">//错误，传递给&amp;的必须是左值</span></span><br></pre></td></tr></table></figure>
<p>f2为const的普通引用</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="function"><span class="type">void</span> <span class="title">f2</span><span class="params">(<span class="type">const</span> T&amp;)</span></span>; <span class="comment">//实参是一个左值或右值</span></span><br><span class="line"><span class="built_in">f2</span>(i);  <span class="comment">//i是一个int，则T为int</span></span><br><span class="line"><span class="built_in">f2</span>(ci); <span class="comment">//ci是一个const int;则T为int</span></span><br><span class="line"><span class="built_in">f2</span>(<span class="number">5</span>);  <span class="comment">//正确，T是一个int</span></span><br></pre></td></tr></table></figure>

<p><strong>从右值引用函数参数推断类型</strong><br>右值引用的类型推断类似左值引用。如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="function"><span class="type">void</span> <span class="title">f3</span><span class="params">(T&amp;&amp;)</span></span>;</span><br><span class="line"><span class="built_in">f3</span>(<span class="number">42</span>); <span class="comment">//实参是一个int类型的右值；模板参数T是int</span></span><br></pre></td></tr></table></figure>
<p><strong>将右值引用绑定到左值的例外</strong><br>通常不能将一个右值引用绑定到一个左值上，但C++在正常的绑定规则下定义了两个例外规则：一个是当将一个左值（如变量i）传递给函数的右值引用参数，且此右值引用指向模板类型参数（如T&amp;&amp;）时，编译器推断模板类型参数为实参的左值引用类型，如f3(i)中T类型为int&amp;，而非int。另一个是 <strong>引用折叠</strong>产生的例外使我们可以在模板类型参数上，将一个右值引用绑定到一个左值上，通常不能创建引用的引用，但可以通过类型别名或模板类型参数间接定义引用的引用。当间接创建一个引用的引用时，这些引用将发生“折叠”，除了右值引用的右值引用会折叠成右值引用之外，其他所有情况下，引用的引用都会折叠成一个普通的左值引用。如：</p>
<ul>
<li>X&amp; &amp;、X&amp; &amp;&amp;和X&amp;&amp; &amp;都折叠成类型X&amp;</li>
<li>类型X&amp;&amp; &amp;&amp;折叠成X&amp;&amp;<br>如上面定义的变量及f3：<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">f3</span>(i);   <span class="comment">//T将为int&amp;</span></span><br><span class="line"><span class="built_in">f3</span>(ci);     <span class="comment">//T是一个const int&amp;</span></span><br></pre></td></tr></table></figure>
这种右值引用的例外将导致：</li>
<li><em>如果一个函数参数是指向模板参数类型的右值引用（如，T&amp;&amp;），则可以传递给它任意类型的实参。如果将一个左值传递给这样的参数，则函数参数被实例化为一个普通的左值引用（T&amp;）。*</em><br>右值引用通常用于两种情况：模板转发其实参或模板被重载</li>
</ul>
<p>C++11中 <strong>std::move的工作方式表明可以使用static_cast显式地将一个左值转换为一个右值引用</strong>，通常情况下static_cast只能用于合法的类型转换，所以这也是一条针对右值引用的特许规则。使用方法如std::move的定义：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在返回类型和类型转换中需要用typename指明成员是一个类型而不是成员变量名称</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="keyword">typename</span> remove_reference&lt;T&gt;::<span class="function">type&amp;&amp; <span class="title">move</span><span class="params">(T&amp;&amp; t)</span>  <span class="comment">//前面的typename是告诉编译器type是个类型而不是成员变量名</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">static_cast</span>&lt;<span class="keyword">typename</span> remove_reference&lt;T&gt;::type&amp;&amp;&gt;(t);  <span class="comment">//typename同样是告诉编译器type是一个类型而不是成员变量名</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>当通过模板使用模板类中的类型时，需要使用typename指定此时引用的是个类型，而不是成员变量名</strong><br>例如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">std::vector&lt;T&gt; vec;</span><br><span class="line"><span class="keyword">typename</span> std::vector&lt;T&gt;::iterator it = vec.<span class="built_in">begin</span>();  <span class="comment">//此时需要通过typename指定iterator是个类型，而不是一个变量名</span></span><br></pre></td></tr></table></figure>

<h3 id="参数转发"><a href="#参数转发" class="headerlink" title="参数转发"></a>参数转发</h3><p>1.参数转发即指将函数的一个或多个实参连同类型等所有性质保持不变地转发给其他函数，包括实参类型是否是const，以及实参是左值还是右值。<br><strong>如果一个函数参数是指向模板类型参数的右值引用（如T&amp;&amp;），它对应的实参的const属性和左传/右值属性将得到保持</strong></p>
<p>2.C++11中可以使用std::forward保持类型信息。std::forward类似move，定义在头文件utility中，与move不同的时，forward必须通过显式模板实参来调用，forward返回该显式实参类型的右值引用，即forward<T>的返回类型是T&amp;&amp;。<br><strong>当用于一个指向模板参数类型的右值引用函数参数（T&amp;&amp;）时，forward会保持实参类型的所有细节</strong><br>如下面的函数flip将其参数t1、t2传递给函数f：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> F, <span class="keyword">typename</span> T1, <span class="keyword">typename</span> T2&gt;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">flip</span><span class="params">(F f, T1 &amp;&amp;t1, T2 &amp;&amp;t2)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="built_in">f</span>(std::forward&lt;T2&gt;(t2), std::forward&lt;T1&gt;(t1));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>调用：<code>flip(g, i, 42);</code>，i将以int&amp;类型传递给g，42将以int&amp;&amp;类型传递给g</p>
<h2 id="重载与模板"><a href="#重载与模板" class="headerlink" title="重载与模板"></a>重载与模板</h2><p>函数模板可以被另一个模板或一个普通模板函数重载。<br>涉及有函数模板的重载，在函数匹配时，如果即有非模板函数又有模板函数时，会优先选择非模板函数。当有多个函数模板可选择时，会在类型转换的情况下，优先选择更特例化的模板。<br><strong>在定义任何函数之前，记得声明所有重载的函数版本。这样就不必担心编译器由于未遇到你希望调用的函数而实例化一个并非你需要的版本</strong></p>
<h2 id="可变参数模板"><a href="#可变参数模板" class="headerlink" title="可变参数模板"></a>可变参数模板</h2><p>1.一个可变参数模板就是一个可以接受可变数目参数的模板函数或模板类，当然这里我们只会用到模板函数。可变数目的参数被称为参数包，包括模板参数包（由0个多或多个类型组成）和函数参数包（由0个或多个函数参数组成）。可变参数的函数模板声明通常形如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Args是一个模板参数包，rest是一个函数参数包</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T, <span class="keyword">typename</span> ... Args&gt;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">func</span><span class="params">(<span class="type">const</span> T &amp;t, <span class="type">const</span> Args&amp; ... rest)</span></span>;  <span class="comment">//扩展Args</span></span><br></pre></td></tr></table></figure>
<p>用一个省略号来指出一个模板参数或函数参数表示一个包。在一个模板参数列表中，class…或typename…指出接下来的参数表示0个或多个类型的列表；一个类型名后面跟一个省略号表示零个或多个给定类型的非类型参数的列表。<br>也就是<code>typename 省略号（...） 模板参数包名字</code>来定义一个模板参数包，<code>扩展模式 模板包名字 省略号（...） 函数参数包名字</code>来将模板包扩展成相应模式下的函数参数包，同样当将函数参数包名字后跟省略号时，即可扩展函数参数包。当编译器在对模板特例化时，会自动按照提供给参数包的模式进行扩展包，扩展之后的参数相当于一个以逗号分隔的参数列表，如上例中const Arg&amp;会应用到模板参数包Args中的每一个元素，也就是最终rest中包含的所有元素都将是const的引用，类型由编译器根据传递的参数进行自动推断。</p>
<p>2.与可变参数模板对应的还有一个sizeof…运算符，用于返回参数包中的参数个数，当然可以用它来配合递归函数访问各参数。<br>注意可变参数模板的使用不需要再指定类型，具体类型由编译器根据传递给函数的实参进行推断。<br>3.当需要在函数内部访问各参数列表中的参数时，直接对函数参数包进行扩展即可，通常是采用递归的方式访问各参数，为了终止递归就需要定义一个重载的函数用于终止递归<br>下面还是以一个计算和的例子分析：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T, <span class="keyword">typename</span>... Args&gt;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">foo</span><span class="params">(<span class="type">const</span> T &amp;t, <span class="type">const</span> Args&amp; ... args)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    std::cout &lt;&lt; <span class="string">&quot;sizeof...(Args): &quot;</span> &lt;&lt; <span class="keyword">sizeof</span>...(Args) &lt;&lt; std::endl;  <span class="comment">//输出模板参数Args的个数</span></span><br><span class="line">    std::cout &lt;&lt; <span class="string">&quot;sizeof...(args): &quot;</span> &lt;&lt; <span class="keyword">sizeof</span>...(args) &lt;&lt; std::endl; <span class="comment">//输出函数参数args的个数</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="function">std::ostream&amp; <span class="title">print</span><span class="params">(std::ostream &amp;os, <span class="type">const</span> T &amp;t)</span>    <span class="comment">//用于结束递归，当参数个数为2个时调用</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> os &lt;&lt; t &lt;&lt; std::endl;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T, <span class="keyword">typename</span> ... Args&gt;</span><br><span class="line"><span class="function">std::ostream&amp; <span class="title">print</span><span class="params">(std::ostream &amp;os, <span class="type">const</span> T &amp;t, Args ... rest)</span>  <span class="comment">//当参数个数大于2个时调用</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    os &lt;&lt; t &lt;&lt; <span class="string">&quot;, &quot;</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">print</span>(os, rest...);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="function">T <span class="title">sum_template</span><span class="params">(<span class="type">const</span> T &amp;t)</span>   <span class="comment">//声明一个重载的固定参数数目的函数，用于结束递归</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> t;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T, <span class="keyword">typename</span>... Args&gt;</span><br><span class="line"><span class="function">T <span class="title">sum_template</span><span class="params">(<span class="type">const</span> T &amp;t, <span class="type">const</span> Args&amp;... args)</span>   <span class="comment">//该函数通过调用仅含一个参数的重载函数来结束递归</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span>  <span class="built_in">sum_template</span>(args...) + t;  <span class="comment">//展开函数参数包args中的实参</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">foo</span>(<span class="string">&#x27;a&#x27;</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="string">&quot;ssl&quot;</span>);</span><br><span class="line">    <span class="built_in">print</span>(std::cout, <span class="string">&#x27;a&#x27;</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="string">&quot;ssl&quot;</span>);</span><br><span class="line">    std::cout &lt;&lt; <span class="built_in">sum_template</span>(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>) &lt;&lt; std::endl;</span><br><span class="line">    std::cout &lt;&lt; <span class="built_in">sum_template</span>(<span class="number">1.1</span>, <span class="number">2.5</span>, <span class="number">3</span>, <span class="number">4.4</span>, <span class="number">5</span>) &lt;&lt; std::endl;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出结果为：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">sizeof...(Args): 3</span><br><span class="line">sizeof...(args): 3</span><br><span class="line">a, 2, 3, ssl</span><br><span class="line">15</span><br><span class="line">15.6</span><br></pre></td></tr></table></figure>
<p>根据后面的求和输出结果可见，对于将double与int混合计算时结果是错误的，因为计算过程中发生了double到int的转换，导致精度损失，所以对于这种情况要注意类型转换问题。</p>
<h3 id="包扩展"><a href="#包扩展" class="headerlink" title="包扩展"></a>包扩展</h3><p>1.对于一个参数包，除了获取其大小外，唯一对它能做的就是扩展（expand），当扩展一个包时，需要提供用于每个扩展元素的模式（pattern），扩展一个包就是将它分解为构成的元素，对每个元素应用模式，获得扩展后的列表。通过在模式右边放一个省略号（…）来触发扩展操作。<br>2.包扩展除了上面用到的将函数参数包中的每个元素应用模式const &amp;这类属性之外，还支持更复杂的扩展，例如对每个元素调用某个函数：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span>... Args&gt;</span><br><span class="line"><span class="function">ostream &amp;<span class="title">errorMsg</span><span class="params">(ostream &amp;os, <span class="type">const</span> Args&amp;... rest)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">print</span>(os, <span class="built_in">debug_rep</span>(rest)...);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对rest参数包中的每个元素调用函数debug_rep</p>
<p><strong>转发参数包</strong><br>C++11中可以使用forward转发参数包。如<code>std::forward&lt;Args&gt;(args)...</code>转发类型为Args的参数包args中的类型参数。</p>
<h2 id="模板特例化"><a href="#模板特例化" class="headerlink" title="模板特例化"></a>模板特例化</h2><p>1.一个模板特例化（template specialization）版本就模板的一个独立的定义，在其中一个或多个模板参数被指定为特定的类型</p>
<h3 id="函数模板特例化"><a href="#函数模板特例化" class="headerlink" title="函数模板特例化"></a>函数模板特例化</h3><p>2.定义函数模板的特例化版本时，必须为原模板中的每个模板参数都提供实参。为了指定我们正在实例化一个模板，应使用template后跟一个空尖括号对（<code>&lt;&gt;</code>），空尖括号指出我们将为原模板的所有模板参数提供实参:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//原模板</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="function"><span class="type">int</span> <span class="title">compare</span><span class="params">(<span class="type">const</span> T&amp;, <span class="type">const</span> T&amp;)</span></span>;</span><br><span class="line"><span class="comment">//compare的特殊版本，处理字符数组的指针</span></span><br><span class="line"><span class="keyword">template</span> &lt;&gt;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">compare</span><span class="params">(<span class="type">const</span> <span class="type">char</span>* <span class="type">const</span> &amp;p1, <span class="type">const</span> <span class="type">char</span>* <span class="type">const</span> &amp;p2)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">strcmp</span>(p1, p2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>特例化的本质是实例化一个模板，而非重载它，因此特例化不影响函数匹配</strong><br>为了特例化一个模板，原模板的声明必须在作用域中，所以模板及其特例化版本应该声明在同一个头文件中。所有同名模板的声明应该放在前面，然后是这些模板的特例化版本。</p>
<h3 id="类模板特例化"><a href="#类模板特例化" class="headerlink" title="类模板特例化"></a>类模板特例化</h3><p>1.类模板特例化时，必须在原模板定义所在命名空间中特例化它。当特例化类模板的所有模板参数时，定义方式与函数模板特例化类似。<br>2.<strong>类模板支持部分特例化</strong>。一个类模板的部分特例化（partial specialization）本身是一个模板，所以使用时必须提供那个未指定的模板参数。如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//原始的通常版本</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">class</span> <span class="title class_">T</span>&gt; strcut remove_reference &#123;</span><br><span class="line">  <span class="keyword">typedef</span> T type;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//部分特例化版本，将用于左值引用和右值引用</span></span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">class</span> <span class="title class_">T</span>&gt; strcut remove_reference&lt;T&amp;&gt; &#123; <span class="comment">//左值引用</span></span><br><span class="line">  <span class="keyword">typedef</span> T type;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">class</span> <span class="title class_">T</span>&gt; strcut remove_reference&lt;T&amp;&amp;&gt; &#123; <span class="comment">//右值引用</span></span><br><span class="line">  <span class="keyword">typedef</span> T type;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>调用：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">remove_reference&lt;(<span class="keyword">decltype</span>(<span class="number">42</span>))&gt;::type a;  <span class="comment">//使用原始版本</span></span><br><span class="line">remove_reference&lt;(<span class="keyword">decltype</span>(i))&gt;::type b;  <span class="comment">//i为int类型变量，使用第一个部分特例化版本</span></span><br><span class="line">remove_reference&lt;(<span class="keyword">decltype</span>(std::<span class="built_in">move</span>(i)))&gt;::type c;  <span class="comment">//i为int类型变量，使用第二个部分特例化版本</span></span><br></pre></td></tr></table></figure>
<p>也可以只 <strong>特例化成员而不是类</strong>，如下Foo是一个模板，包含一个成员Bar，后面将只特例化该成员：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; <span class="keyword">struct</span> <span class="title class_">Foo</span> &#123;</span><br><span class="line">  <span class="built_in">Foo</span>(<span class="type">const</span> T &amp;t = <span class="built_in">T</span>()) : <span class="built_in">mem</span>(t) &#123;&#125;</span><br><span class="line">  <span class="function"><span class="type">void</span> <span class="title">Bar</span><span class="params">()</span> </span>&#123;<span class="comment">/*...*/</span>&#125;</span><br><span class="line">  T mem;</span><br><span class="line">  <span class="comment">//other member</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//特例化成员Bar</span></span><br><span class="line"><span class="keyword">template</span>&lt;&gt;    <span class="comment">//表示正在特例化一个模板</span></span><br><span class="line"><span class="type">void</span> Foo&lt;<span class="type">int</span>&gt;::<span class="built_in">Bar</span>()  <span class="comment">//表示正在特例化Foo&lt;int&gt;的成员Bar</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">//其他应用于int的特例化处理</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    
        

  <div class="followme">
    <p>Welcome to my other publishing channels</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Notes/" rel="tag"># Notes</a>
              <a href="/tags/CPP-OOP/" rel="tag"># CPP-OOP</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2016/01/13/cpp-oop-object-oriented/" rel="prev" title="C++学习笔记之面向对象程序设计">
      <i class="fa fa-chevron-left"></i> C++学习笔记之面向对象程序设计
    </a></div>
      <div class="post-nav-item">
    <a href="/2016/02/19/linux-command-tools-sed/" rel="next" title="Linux实用工具总结之sed">
      Linux实用工具总结之sed <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E6%A8%A1%E6%9D%BF"><span class="nav-number">1.</span> <span class="nav-text">函数模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%B1%BB%E6%A8%A1%E6%9D%BF"><span class="nav-number">2.</span> <span class="nav-text">类模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A8%A1%E6%9D%BF%E4%B8%8E%E5%8F%8B%E5%85%83"><span class="nav-number">3.</span> <span class="nav-text">模板与友元</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A8%A1%E6%9D%BF%E5%8F%82%E6%95%B0"><span class="nav-number">4.</span> <span class="nav-text">模板参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%88%90%E5%91%98%E6%A8%A1%E6%9D%BF"><span class="nav-number">5.</span> <span class="nav-text">成员模板</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%99%AE%E9%80%9A%EF%BC%88%E9%9D%9E%E6%A8%A1%E6%9D%BF%EF%BC%89%E7%B1%BB%E7%9A%84%E6%88%90%E5%91%98%E6%A8%A1%E6%9D%BF"><span class="nav-number">5.1.</span> <span class="nav-text">普通（非模板）类的成员模板</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%B1%BB%E6%A8%A1%E6%9D%BF%E7%9A%84%E6%88%90%E5%91%98%E6%A8%A1%E6%9D%BF"><span class="nav-number">5.2.</span> <span class="nav-text">类模板的成员模板</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8extern%E6%8E%A7%E5%88%B6%E5%AE%9E%E4%BE%8B%E5%8C%96"><span class="nav-number">6.</span> <span class="nav-text">使用extern控制实例化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A8%A1%E6%9D%BF%E5%AE%9E%E5%8F%82%E6%8E%A8%E6%96%AD"><span class="nav-number">7.</span> <span class="nav-text">模板实参推断</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8C%87%E5%AE%9A%E6%98%BE%E5%BC%8F%E6%A8%A1%E6%9D%BF%E5%AE%9E%E5%8F%82"><span class="nav-number">7.1.</span> <span class="nav-text">指定显式模板实参</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B0%BE%E7%BD%AE%E8%BF%94%E5%9B%9E%E7%B1%BB%E5%9E%8B%E4%B8%8E%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="nav-number">7.2.</span> <span class="nav-text">尾置返回类型与类型转换</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E6%8C%87%E9%92%88%E4%B8%8E%E5%AE%9E%E5%8F%82%E6%8E%A8%E6%96%AD"><span class="nav-number">7.3.</span> <span class="nav-text">函数指针与实参推断</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E6%A8%A1%E6%9D%BF%E5%AE%9E%E5%8F%82%E6%8E%A8%E6%96%AD%E4%B8%8E%E5%BC%95%E7%94%A8"><span class="nav-number">7.4.</span> <span class="nav-text">函数模板实参推断与引用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E6%95%B0%E8%BD%AC%E5%8F%91"><span class="nav-number">7.5.</span> <span class="nav-text">参数转发</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%87%8D%E8%BD%BD%E4%B8%8E%E6%A8%A1%E6%9D%BF"><span class="nav-number">8.</span> <span class="nav-text">重载与模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0%E6%A8%A1%E6%9D%BF"><span class="nav-number">9.</span> <span class="nav-text">可变参数模板</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8C%85%E6%89%A9%E5%B1%95"><span class="nav-number">9.1.</span> <span class="nav-text">包扩展</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A8%A1%E6%9D%BF%E7%89%B9%E4%BE%8B%E5%8C%96"><span class="nav-number">10.</span> <span class="nav-text">模板特例化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E6%A8%A1%E6%9D%BF%E7%89%B9%E4%BE%8B%E5%8C%96"><span class="nav-number">10.1.</span> <span class="nav-text">函数模板特例化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%B1%BB%E6%A8%A1%E6%9D%BF%E7%89%B9%E4%BE%8B%E5%8C%96"><span class="nav-number">10.2.</span> <span class="nav-text">类模板特例化</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="blueyi"
      src="/images/default_avatar.jpg">
  <p class="site-author-name" itemprop="name">blueyi</p>
  <div class="site-description" itemprop="description">心怀善意，虛怀若谷！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">104</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">68</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/blueyi" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;blueyi" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://maxwi.com/" title="http:&#x2F;&#x2F;maxwi.com" rel="noopener" target="_blank">Maxwi</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2014 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">blueyi</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="Symbols count total">750k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="Reading time total">11:22</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  
  <script data-pjax>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '0f8243eb2c8b2207980f',
      clientSecret: 'd159633a33519d3b7a48b0ca729032f7d1f38a41',
      repo        : 'notes',
      owner       : 'blueyi',
      admin       : ['blueyi'],
      id          : '68a2892b5a63eb59e2c6824899670ca5',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

    </div>
</body>
</html>
